//
//  HistoryViewController.m
//  SnapCAD
//
//  Created by Developer on 2025/1/27.
//

#import "HistoryViewController.h"
#import "Snmodel.h"
#import "SnDataSourceTool.h"
#import "SnToolManager.h"
#import "Masonry.h"

@interface HistoryViewController () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIButton *backButton;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *emptyStateView;
@property (nonatomic, strong) NSArray<Snmodel *> *historyData;

@end

@implementation HistoryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self setupConstraints];
    [self loadHistoryData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    [self loadHistoryData]; // 重新加载数据以确保最新
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)setupUI {
    self.view.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.97 alpha:1.0];
    
    [self setupHeader];
    [self setupTableView];
    [self setupEmptyStateView];
}

- (void)setupHeader {
    // 头部视图
    self.headerView = [[UIView alloc] init];
    self.headerView.backgroundColor = [UIColor whiteColor];
    
    // 添加阴影
    self.headerView.layer.shadowColor = [UIColor blackColor].CGColor;
    self.headerView.layer.shadowOffset = CGSizeMake(0, 2);
    self.headerView.layer.shadowOpacity = 0.1;
    self.headerView.layer.shadowRadius = 4;
    
    self.headerView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.headerView];
    
    // 返回按钮
    self.backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.backButton setImage:[UIImage systemImageNamed:@"chevron.left"] forState:UIControlStateNormal];
    self.backButton.tintColor = [UIColor colorWithRed:0.40 green:0.49 blue:0.93 alpha:1.0];
    [self.backButton addTarget:self action:@selector(backButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    self.backButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.headerView addSubview:self.backButton];
    
    // 标题标签
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.text = @"History";
    self.titleLabel.font = [UIFont boldSystemFontOfSize:18];
    self.titleLabel.textColor = [UIColor blackColor];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.headerView addSubview:self.titleLabel];
}

- (void)setupTableView {
    // 表格视图
    self.tableView = [[UITableView alloc] init];
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.showsVerticalScrollIndicator = NO;
    
    // 注册cell
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"HistoryCell"];
    
    self.tableView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.tableView];
}

- (void)setupEmptyStateView {
    // 空状态视图
    self.emptyStateView = [[UIView alloc] init];
    self.emptyStateView.backgroundColor = [UIColor clearColor];
    self.emptyStateView.hidden = YES;
    
    // 空状态图标
    UIImageView *emptyIconView = [[UIImageView alloc] init];
    emptyIconView.image = [UIImage systemImageNamed:@"doc.text"];
    emptyIconView.tintColor = [UIColor lightGrayColor];
    emptyIconView.contentMode = UIViewContentModeScaleAspectFit;
    emptyIconView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.emptyStateView addSubview:emptyIconView];
    
    // 空状态标题
    UILabel *emptyTitleLabel = [[UILabel alloc] init];
    emptyTitleLabel.text = @"No History";
    emptyTitleLabel.font = [UIFont boldSystemFontOfSize:18];
    emptyTitleLabel.textColor = [UIColor lightGrayColor];
    emptyTitleLabel.textAlignment = NSTextAlignmentCenter;
    emptyTitleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.emptyStateView addSubview:emptyTitleLabel];
    
    // 空状态描述
    UILabel *emptyDescLabel = [[UILabel alloc] init];
    emptyDescLabel.text = @"After opening CAD files, history will be displayed here";
    emptyDescLabel.font = [UIFont systemFontOfSize:14];
    emptyDescLabel.textColor = [UIColor lightGrayColor];
    emptyDescLabel.textAlignment = NSTextAlignmentCenter;
    emptyDescLabel.numberOfLines = 0;
    emptyDescLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.emptyStateView addSubview:emptyDescLabel];
    
    self.emptyStateView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.emptyStateView];
    
    // 空状态视图约束
    [emptyIconView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.emptyStateView);
        make.centerY.equalTo(self.emptyStateView).offset(-40);
        make.size.mas_equalTo(CGSizeMake(60, 60));
    }];
    
    [emptyTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(emptyIconView.mas_bottom).offset(16);
        make.centerX.equalTo(self.emptyStateView);
        make.left.equalTo(self.emptyStateView).offset(40);
        make.right.equalTo(self.emptyStateView).offset(-40);
    }];
    
    [emptyDescLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(emptyTitleLabel.mas_bottom).offset(8);
        make.centerX.equalTo(self.emptyStateView);
        make.left.equalTo(self.emptyStateView).offset(40);
        make.right.equalTo(self.emptyStateView).offset(-40);
    }];
}

- (void)setupConstraints {
    // 头部视图约束
    [self.headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.height.equalTo(@88);
    }];
    
    // 返回按钮约束
    [self.backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.headerView).offset(16);
        make.bottom.equalTo(self.headerView).offset(-10);
        make.size.mas_equalTo(CGSizeMake(44, 44));
    }];
    
    // 标题标签约束
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.headerView);
        make.centerY.equalTo(self.backButton);
    }];
    
    // 表格视图约束
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.headerView.mas_bottom);
        make.left.right.bottom.equalTo(self.view);
    }];
    
    // 空状态视图约束
    [self.emptyStateView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.headerView.mas_bottom);
        make.left.right.bottom.equalTo(self.view);
    }];
}

#pragma mark - Data Loading

- (void)loadHistoryData {
    // 从数据库获取历史数据
    NSArray *allData = [SnDataSourceTool obtainAllData];
    
    // 按日期排序，最新的在前面
    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"timestamp" ascending:NO];
    self.historyData = [allData sortedArrayUsingDescriptors:@[sortDescriptor]];
    
    // 更新UI
    self.emptyStateView.hidden = (self.historyData.count > 0);
    self.tableView.hidden = (self.historyData.count == 0);
    
    [self.tableView reloadData];
}

#pragma mark - UITableView DataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.historyData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HistoryCell" forIndexPath:indexPath];
    
    // 清除之前的子视图
    for (UIView *subview in cell.contentView.subviews) {
        [subview removeFromSuperview];
    }
    
    Snmodel *model = self.historyData[indexPath.row];
    
    // 创建卡片样式的cell内容
    UIView *cardView = [self createHistoryCardWithModel:model];
    [cell.contentView addSubview:cardView];
    
    [cardView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(cell.contentView).offset(8);
        make.left.equalTo(cell.contentView).offset(16);
        make.right.equalTo(cell.contentView).offset(-16);
        make.bottom.equalTo(cell.contentView).offset(-8);
        make.height.equalTo(@80);
    }];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor clearColor];
    
    return cell;
}

#pragma mark - UITableView Delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // 添加点击效果
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    UIView *cardView = cell.contentView.subviews.firstObject;
    
    // 点击动画效果
    [UIView animateWithDuration:0.1 animations:^{
        cardView.transform = CGAffineTransformMakeScale(0.95, 0.95);
        cardView.alpha = 0.8;
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.1 animations:^{
            cardView.transform = CGAffineTransformIdentity;
            cardView.alpha = 1.0;
        } completion:^(BOOL finished) {
            // 打开文件
            Snmodel *model = self.historyData[indexPath.row];
            [SnToolManager pushCADFileWithModel:model navigationController:self.navigationController];
        }];
    }];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    // 添加高亮效果
    UIView *cardView = cell.contentView.subviews.firstObject;
    if (cardView) {
        cardView.layer.shadowColor = [UIColor blackColor].CGColor;
        cardView.layer.shadowOffset = CGSizeMake(0, 2);
        cardView.layer.shadowOpacity = 0.1;
        cardView.layer.shadowRadius = 8;
    }
}

- (void)tableView:(UITableView *)tableView didHighlightRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    UIView *cardView = cell.contentView.subviews.firstObject;
    if (cardView) {
        cardView.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.97 alpha:1.0];
        cardView.layer.shadowOpacity = 0.2;
    }
}

- (void)tableView:(UITableView *)tableView didUnhighlightRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    UIView *cardView = cell.contentView.subviews.firstObject;
    if (cardView) {
        cardView.backgroundColor = [UIColor whiteColor];
        cardView.layer.shadowOpacity = 0.1;
    }
}

- (UIView *)createHistoryCardWithModel:(Snmodel *)model {
    UIView *cardView = [[UIView alloc] init];
    cardView.backgroundColor = [UIColor whiteColor];
    cardView.layer.cornerRadius = 12;
    cardView.clipsToBounds = NO;
    
    // 文件图标
    UIImageView *iconView = [[UIImageView alloc] init];
    iconView.image = [UIImage systemImageNamed:@"doc.text.fill"];
    iconView.tintColor = [UIColor colorWithRed:0.40 green:0.49 blue:0.93 alpha:1.0];
    iconView.contentMode = UIViewContentModeScaleAspectFit;
    [cardView addSubview:iconView];
    
    // 文件名标签
    UILabel *nameLabel = [[UILabel alloc] init];
    nameLabel.text = model.documentName ?: @"Unknown File";
    nameLabel.font = [UIFont boldSystemFontOfSize:16];
    nameLabel.textColor = [UIColor blackColor];
    nameLabel.numberOfLines = 1;
    [cardView addSubview:nameLabel];
    
    // 时间标签
    UILabel *timeLabel = [[UILabel alloc] init];
    timeLabel.text = [self formatTimeFromTimestamp:model.timestamp];
    timeLabel.font = [UIFont systemFontOfSize:12];
    timeLabel.textColor = [UIColor grayColor];
    [cardView addSubview:timeLabel];
    
    // 箭头图标
    UIImageView *arrowView = [[UIImageView alloc] init];
    arrowView.image = [UIImage systemImageNamed:@"chevron.right"];
    arrowView.tintColor = [UIColor lightGrayColor];
    arrowView.contentMode = UIViewContentModeScaleAspectFit;
    [cardView addSubview:arrowView];
    
    // 约束设置
    [iconView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(cardView).offset(16);
        make.centerY.equalTo(cardView);
        make.size.mas_equalTo(CGSizeMake(32, 32));
    }];
    
    [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(iconView.mas_right).offset(12);
        make.top.equalTo(cardView).offset(16);
        make.right.equalTo(arrowView.mas_left).offset(-12);
    }];
    
    [timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(nameLabel);
        make.top.equalTo(nameLabel.mas_bottom).offset(4);
        make.right.equalTo(nameLabel);
    }];
    
    [arrowView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(cardView).offset(-16);
        make.centerY.equalTo(cardView);
        make.size.mas_equalTo(CGSizeMake(16, 16));
    }];
    
    return cardView;
}

- (NSString *)formatTimeFromTimestamp:(NSString *)timestamp {
    if (!timestamp || timestamp.length == 0) {
        return @"Unknown time";
    }
    
    NSTimeInterval timeInterval = [timestamp doubleValue];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    // 检查是否是今天
    NSCalendar *calendar = [NSCalendar currentCalendar];
    if ([calendar isDateInToday:date]) {
        [formatter setDateFormat:@"HH:mm"];
        return [NSString stringWithFormat:@"Today %@", [formatter stringFromDate:date]];
    }
    
    // 检查是否是昨天
    if ([calendar isDateInYesterday:date]) {
        [formatter setDateFormat:@"HH:mm"];
        return [NSString stringWithFormat:@"Yesterday %@", [formatter stringFromDate:date]];
    }
    
    // 其他日期
    [formatter setDateFormat:@"MM/dd HH:mm"];
    return [formatter stringFromDate:date];
}

#pragma mark - Button Actions

- (void)backButtonTapped {
    [self.navigationController popViewControllerAnimated:YES];
}

@end
